﻿//-----------------------------------------------------------------------
// <copyright file="WebflowModel.cs" company="Sławomir Rosiek">
//     Copyright (c) Sławomir Rosiek. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Rosieks.Web.Flow.Metadata
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Routing;

    public partial class WebflowModel
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="T:WebflowModel"/> class.
        /// </summary>
        /// <param name="name">Name of the webflow.</param>
        public WebflowModel(string name)
        {
            this.Name = name;
            this.CheckStatePolicy = new GoToCurrentPolicy();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:WebflowModel"/> class.
        /// </summary>
        protected WebflowModel()
            : this(null)
        {
        }

        public ICollection<State> States { get; set; }

        public State FirstState
        {
            get;
            set;
        }

        public ICheckStatePolicy CheckStatePolicy
        {
            get;
            set;
        }

        public State this[string stateName]
        {
            get
            {
                return this.States.FirstOrDefault(e => string.Equals(e.Name, stateName, StringComparison.InvariantCultureIgnoreCase));
            }
        }

        public virtual void OnStart(WebflowContext webflowContext)
        {
            webflowContext.Model = Activator.CreateInstance(this.Model);
        }

        public virtual void OnFinish(WebflowContext webflowContext)
        {
        }

        internal void RegisterRoutes(RouteCollection routes)
        {
            foreach (var route in this.States.Select(s => s.RouteData))
            {
                route.Register(routes, this.Name);
            }
        }

        public IStoreLocationPolicy StoreLocationPolicy { get; set; }
    }

    public abstract class WebflowModel<T> : WebflowModel
    {
        public WebflowModel(string name)
            : base(name)
        {
            this.Model = typeof(T);
        }
    }
}
